package com.dede.rxbase.util;

import android.app.Activity;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 自定义Activity栈管理工具
 *
 * @author hsh
 *         2018/1/9 11:30.
 */
public final class ActivityManager {

    static {
        activities = new LinkedList<>();
    }

    private ActivityManager() {
    }

    private static LinkedList<Activity> activities;// Activity栈集合

    /**
     * 在Activity create时调用当前方法，将当前Activity实例传入
     *
     * @param activity Activity实例
     */
    public static void onCreate(Activity activity) {
        if (activity == null) return;
        activities.add(activity);
    }

    /**
     * 在Activity destroy的时候调用，将当前Activity实例传入
     *
     * @param activity Activity实例
     */
    public static void onDestroy(Activity activity) {
        if (activity == null) return;
        activities.remove(activity);
    }

    /**
     * 关闭某个Activity
     *
     * @param activity Activity实例
     */
    public static void finish(Activity activity) {
        if (activity == null) return;
        finish(activity.getClass());
    }

    /**
     * 关闭某个Activity
     *
     * @param aClass Activity class
     */
    public static void finish(Class<? extends Activity> aClass) {
        if (aClass == null) return;
        for (int i = 0, l = activities.size(); i < l; i++) {
            Activity activity = activities.get(i);
            if (activity == null) {
                activities.remove(i);
                l = activities.size();
                i--;
                continue;
            }
            if (activity.getClass() == aClass) {
                if (!activity.isFinishing())
                    activity.finish();
                break;
            }
        }
    }

    /**
     * 关闭所有的Activity
     */
    public static void finish() {
        ArrayList<Activity> copy = new ArrayList<>(ActivityManager.activities);
        for (Activity activity : copy) {
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
        copy.clear();
    }
}
